package com.example.adabank3.controller;


import com.example.adabank3.entity.CustomerExample;
import com.example.adabank3.entity.Users;
import com.example.adabank3.mapper.CustomerMapper;
import com.example.adabank3.entity.Customer;
import com.example.adabank3.mapper.UsersMapper;
import com.example.adabank3.util.Result;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpSession;
import java.util.*;


/**
 * @author Administrator
 */
@RestController
@RequestMapping("/api")

public class MyController {
    final CustomerMapper customerMapper;
    final UsersMapper usersMapper;

    public MyController(CustomerMapper customerMapper, UsersMapper usersMapper) {
        this.customerMapper = customerMapper;
        this.usersMapper = usersMapper;
    }

    /**
     * 查看状态
     * @return Result<Customer>
     */
    @GetMapping("/status")
    public Result<Customer> status() {
        return Result.of("Successfully inserted a customer!");
    }


    /**
     * 根据id查询一条记录
     * @return Customer
     */
    @RequestMapping("/customers/{id}")
    public Result<Customer> selectId(@PathVariable("id") Integer id) {
        Customer result = customerMapper.selectByPrimaryKey(id);
        return new Result("OK","查询成功",result);
    }
    /**
     * 根据name查询一条记录
     * @return Customer
     */
    @RequestMapping("/users/{username}")
    public Result<Users> selectName(@PathVariable("username") String username) {
        Users users = usersMapper.selectByPrimaryName(username);
        return new Result("OK","查询成功",users);
    }

    /**
     * 根据id删除一条记录(假删除)
     * deleted字段： 0正常  1删除
     * @return Customer
     */
    @DeleteMapping("/customers/{id}")
    public Result<Customer> delete(@PathVariable("id") Integer id) {

        Customer customer = new Customer();
        customer.setId(id);
        customer.setDeleted(1);
        customerMapper.updateByPrimaryKey(customer);
        return new Result("OK","删除成功",null);
    }



    /**
     * 查询所有列表
     * @return List<Customer>
     */
    @RequestMapping("/customers")
    @CrossOrigin
    public  Result<Customer> select(
            @RequestParam(required = false,defaultValue = "",value = "query")String searchList){


        CustomerExample customer = new CustomerExample();
        CustomerExample.Criteria customers = customer.createCriteria();

        //搜索条件为空，显示所有
        if("{}".equals(searchList)){
            customers.andDeletedEqualTo(0);
            List<Customer> result = customerMapper.selectByExample(customer);
            System.out.println(result);
            return new Result("OK","查询成功",result);
        }

        //截取字符
        String searchParam = searchList.substring(2, searchList.indexOf(":")-1);
        String searchValue = searchList.substring(searchList.indexOf(":")+2,searchList.length()-2);

        //卡号（精确搜索）
        if ("cardNumber".equals(searchParam)){
            customers.andDeletedEqualTo(0);
            customers.andCardNumberEqualTo(searchValue);
            List<Customer> result = customerMapper.selectByExample(customer);
            System.out.println(result);
            return new Result("OK","查询成功",result);
        }
        //最小金额
        if ("minBalance".equals(searchParam)){
            customers.andDeletedEqualTo(0);
            customers.andBalanceLessThan(searchValue);
            List<Customer> result = customerMapper.selectByExample(customer);
            return new Result("OK","查询成功",result);
        }
        //最大金额
        if ("maxBalance".equals(searchParam)){
            customers.andDeletedEqualTo(0);
            customers.andBalanceGreaterThan(searchValue);
            List<Customer> result = customerMapper.selectByExample(customer);
            return new Result("OK","查询成功",result);
        }
        //公司名中包含的关键字
        if ("companyName".equals(searchParam)){
            customers.andDeletedEqualTo(0);
            customers.andCompanyNameLike("%" + searchValue + "%");
            List<Customer> result = customerMapper.selectByExample(customer);
            return new Result("OK","查询成功",result);
        }
        //公司地址中包含的关键字
        if ("companyAddress".equals(searchParam)){
            customers.andDeletedEqualTo(0);
            customers.andCompanyAddressLike("%" + searchValue + "%");
            List<Customer> result = customerMapper.selectByExample(customer);
            return new Result("OK","查询成功",result);
        }
        //业务范围中包含的关键字
        if ("business".equals(searchParam)){
            customers.andDeletedEqualTo(0);
            customers.andBusinessLike("%" + searchValue + "%");
            List<Customer> result = customerMapper.selectByExample(customer);
            return new Result("OK","查询成功",result);
        }
        //法人姓名（精确搜索）
        if ("legalRepName".equals(searchParam)){
            customers.andDeletedEqualTo(0);
            customers.andLegalRelTelEqualTo(searchValue);
            List<Customer> result = customerMapper.selectByExample(customer);
            System.out.println(result);
            return new Result("OK","查询成功",result);
        }
        return new Result("error","数据库没有相关信息",null);
    }


    /**
     * 添加新顾客
     * @return List<Customer>
     */
    @PostMapping("/customers")
    public Result<Customer> addCustomer(@RequestBody Customer customer) {

        customerMapper.insertSelective(customer);
        return Result.of("OK");

    }

    /**
     * 编辑顾客
     * @return List<Customer>
     */
    @PostMapping("/customers/{id}")
    public Result<Customer> editCustomer(@RequestBody Customer customer) {

        Customer newCustomer = new Customer();
        newCustomer.setId(customer.getId());
        newCustomer.setDeleted(customer.getDeleted());
        newCustomer.setBalance(customer.getBalance());
        newCustomer.setUsername(customer.getUsername());
        newCustomer.setCompanyName(customer.getCompanyName());
        newCustomer.setCardNumber(customer.getCardNumber());
        newCustomer.setCompanyAddress(customer.getCompanyAddress());
        newCustomer.setCompanyCreditCode(customer.getCompanyCreditCode());
        newCustomer.setLegalRepName(customer.getLegalRepName());
        newCustomer.setLegalRepId(customer.getLegalRepId());
        newCustomer.setLegalRepAddr(customer.getLegalRepAddr());
        newCustomer.setLegalRepTel(customer.getLegalRepTel());
        newCustomer.setBusiness(customer.getBusiness());
        customerMapper.updateByPrimaryKey(newCustomer);
        return Result.of("OK");

    }

    @PostMapping("/login")
    public Result<Users> login(@RequestBody Map<String, String> data, HttpSession session) {

        String username = data.get("username");
        String password = data.get("password");
        Result result = new Result<Users>();
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        System.out.println("controller:" + token);
        try {
            //执行登录方法
            System.out.println("登录方法执行前");
            subject.login(token);
            session.setAttribute("username",username);
            System.out.println("执行了登录");
        } catch (UnknownAccountException e) {
            System.out.println("用户名不存在");
            result.setStatus("ERRO");
            result.setMessage("用户名不存在，请检查用户名");
            return result;
        } catch (AuthenticationException e) {
            System.out.println("认证失败");
            result.setStatus("ERRO");
            result.setMessage("认证失败，请检查用户名");
            return result;
        }
        result.setStatus("OK");
        result.setMessage("登录成功");
        return result;
    }

    @RequestMapping("/unauth")
    @ResponseBody
    public String unauth(){
        return "未授权没有访问权限";
    }
    /**
     * 检测是否为登录状态
     * @return OK
     */
    @GetMapping("/me")
    public Result<Users> me(HttpSession session) {
        //获取当前用户
        String username = (String) session.getAttribute("username");
        if (username != null) {
            return new Result("OK","YES-LOGIN",username);
        }else {
            return new Result("EOOR","NO-LOGIN",null);
        }

    }
    @PostMapping("/logout")
    public Result<Users> logout(HttpSession session) {
        session.removeAttribute("username");
        return new Result<>("OK",null,null);
    }

}